// abnormallyReport.js
var app = getApp();
var url = app.url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    faultList: [{
        name: '单灯不亮',
        value: '单灯不亮'
      },
      {
        name: '线路故障',
        value: '线路故障'
      },
      {
        name: '控制箱故障',
        value: '控制箱故障'
      },
      {
        name: '灯杆门缺损',
        value: '灯杆门缺损'
      },
      {
        name: '灯杆缺陷',
        value: '灯杆缺陷'
      },
      {
        name: '乱挂广告牌',
        value: '乱挂广告牌'
      },
      {
        name: '紧急突发故障',
        value: '紧急突发故障'
      },
      {
        name: '控制箱维护',
        value: '控制箱维护'
      },
      {
        name: '其它故障隐患',
        value: '其它故障隐患'
      },
    ],
    faultItems: {
      '单灯不亮': [{
          name: '更换灯具',
          value: '更换灯具'
        },
        {
          name: '更换平行线',
          value: '更换平行线'
        },
        {
          name: '重接老化电线',
          value: '重接老化电线'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '线路故障': [{
          name: '单灯漏电',
          value: '单灯漏电'
        },
        {
          name: '线路漏电',
          value: '线路漏电'
        },
        {
          name: '软故障',
          value: '软故障'
        },
        {
          name: '线路短路',
          value: '线路短路'
        },
        {
          name: '平行线短路',
          value: '平行线短路'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '灯杆门缺损': [{
          name: '重新安装灯杆门',
          value: '重新安装灯杆门'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '灯杆缺陷': [{
          name: '调杆',
          value: '调杆'
        },
        {
          name: '调支架',
          value: '调支架'
        },
        {
          name: '拆除被撞灯杆',
          value: '拆除被撞灯杆'
        },
        {
          name: '重立被撞灯杆',
          value: '重立被撞灯杆'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '乱挂广告牌': [{
          name: '拆除广告牌',
          value: '拆除广告牌'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '乱挂广告牌': [{
          name: '拆除广告牌',
          value: '拆除广告牌'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '控制箱故障': [{
          name: '更换熔芯',
          value: '更换熔芯'
        },
        {
          name: '更换交流接触器',
          value: '更换交流接触器'
        },
        {
          name: '更换空气开关',
          value: '更换空气开关'
        },
        {
          name: '更换时控器',
          value: '更换时控器'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '控制箱维护': [{
          name: '除草',
          value: '除草'
        },
        {
          name: '除尘',
          value: '除尘'
        },
        {
          name: '上锁',
          value: '上锁'
        },
        {
          name: '安健环',
          value: '安健环'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ]
    },
    measures: {
      '单灯漏电': [{
          name: '更换灯具',
          value: '更换灯具'
        },
        {
          name: '更换平行线',
          value: '更换平行线'
        },
        {
          name: '重接老化线',
          value: '重接老化线'
        },
        {
          name: '剪除平行线',
          value: '剪除平行线'
        },
        {
          name: '其它故障',
          value: '其它故障'
        },
      ],
      '软故障': [{
          name: '正常亮灯待观察',
          value: '正常亮灯待观察'
        },
        {
          name: '其它措施',
          value: '其它措施'
        },
      ],
      '线路短路': [{
          name: '重接破损电缆',
          value: '重接破损电缆'
        },
        {
          name: '短路仪定点接线',
          value: '短路仪定点接线'
        },
        {
          name: '更换整档电缆',
          value: '更换整档电缆'
        },
        {
          name: '改放架空线供电',
          value: '改放架空线供电'
        },
        {
          name: '改相',
          value: '改相'
        },
        {
          name: '其它措施',
          value: '其它措施'
        },
      ],
      '平行线短路': [{
          name: '剪除平行线',
          value: '剪除平行线'
        },
        {
          name: '更换平行线',
          value: '更换平行线'
        },
        {
          name: '其它措施',
          value: '其它措施'
        },
      ],
      '线路漏电': [{
          name: '重接破损电缆',
          value: '重接破损电缆'
        },
        {
          name: '短路仪定点接线',
          value: '短路仪定点接线'
        },
        {
          name: '更换整档电缆',
          value: '更换整档电缆'
        },
        {
          name: '改放架空线供电',
          value: '改放架空线供电'
        },
        {
          name: '改相',
          value: '改相'
        },
        {
          name: '其它情况',
          value: '其它情况'
        },
      ],
      '更换灯具': [{
          name: '30W',
          value: '30W'
        },
        {
          name: '60W',
          value: '60W'
        },
        {
          name: '100W',
          value: '100W'
        },
        {
          name: '180W',
          value: '180W'
        },
        {
          name: '射灯',
          value: '射灯'
        },
        {
          name: '庭院灯',
          value: '庭院灯'
        },
      ],
    },
    gzList: ['路灯不亮', '周边路灯不亮', '架空线断落下锤', '灯杆盖缺失', '灯杆损坏倾斜', '其它故障'],
    xlItems: [{
        name: '漏电',
        value: '漏电'
      },
      {
        name: '短路',
        value: '短路'
      },
      {
        name: '施工开挖',
        value: '施工开挖'
      },
      {
        name: '被盗',
        value: '被盗'
      },
      {
        name: '控制箱故障',
        value: '控制箱故障'
      },
      {
        name: '上级电源故障',
        value: '上级电源故障'
      },
      {
        name: '架空线断落',
        value: '架空线断落'
      },
    ],
    pdxWx: {
      '更换熔芯': [{
          name: 'A',
          value: ''
        },
        {
          name: '个',
          value: ''
        },
      ],
      '更换交流接触器': [{
          name: 'A',
          value: ''
        },
        {
          name: '个',
          value: ''
        },
      ],
      '拔掉漏电熔芯': [{
        name: '个',
        value: ''
      }, ],
      '拔掉线路故障熔芯': [{
        name: '个',
        value: ''
      }, ],
      '更换空气开关': [{
        name: '个',
        value: ''
      }, ],
      '更换时控器': [{
        name: '个',
        value: ''
      }, ],
    },
    xlList: ['漏电', '短路', '施工开挖', '被盗', '控制箱故障', '上级电源故障', '架空线断落'],
    faultDescription: "",
    canRemark: false,
    str1: ['a'],
    str2: 'a',
    facilitiesNo: '', //设施编号
    streetLampType: '', //路灯类型
    address: '', //地址
    jwdInfo: '', //经纬度
    // powerUnit: '',//权属单位
    name: wx.getStorageSync('nickname'),
    phone: '',
    deptid: 0, //部门id
    loading: false,
    userInfo: {},
    exlist: [],
    radioVal: '',
    exobj: {},
    moreChflag: true,
    id: '',
    type: 0,
    tittleInfo: '',
    mapshow: true,
    longitude: 113.324520,
    latitude: 23.099994,
    remark: '',
    streetLampId: '',
    hasScene: false,
    imgshow: [],
    imgUrl: [],
    faultChangeValue: '',
    faultDescriptionInput: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    this.setData({
      id: options.id
    })
    this.checkLogin()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserInfo();
    var that = this;
    var scene = that.data.id;
    if (scene != '') {
      //查询故障信息
      // that.searchEX(scene);
    } else {
      //需要登录系统账号信息
      // that.checkLogin();
    }
  },
  onShareAppMessage: function () {

  },
  getUserInfo: function () {
    var that = this
    wx.getUserInfo({
      lang: 'zh_CN',
      success: function (res) {

      },
      fail: function (res) {
        wx.showModal({
          title: '需要您授权才能正常显示',
          content: '请点击“去授权”并点击授权按钮，即可正常使用',
          confirmText: '去授权',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              // wx.openSetting({
              //   success: function (re) {
              //     if (!re.authSetting["scope.userInfo"] || !re.authSetting["scope.userLocation"]) {
              //       var isset = that.data.isSetUserInfo
              //       if(!isset){
              //         that.getUserInfo()
              //       }
              //     }else{
              //       that.setData({ isSetUserInfo : true})
              //     }
              //   }
              // })
              console.log("用户点击确定")
              wx.navigateTo({
                url: '../authorize/authorize',
              })
            }
          }
        })
      }
    })
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName');
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //当获取焦点时触发
  focusFun: function (e) {
    var that = this;
    var param = e.target.dataset.param;
    that.searchEXlist();
    var val = 0;
    var tittle = '终端编号选择';
    if (param == 1) {
      val = 1;
      tittle = '终端编号选择';
    } else if (param == 3) {
      val = 3;
      tittle = '地址选择';
    } else if (param == 4) {
      val = 4;
      tittle = '经纬度选择';
    }
    that.setData({
      type: val,
      tittleInfo: tittle
    });
  },
  //根据id查询
  searchEX: function (id) {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded'
    };
    var param = {
      id: id
    };
    wx.request({
      url: app.url + '/web/exceptionReport/getById.htm',
      data: app.ecbEncrypto(param),
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          var entity = rest.result;
          that.setData({
            facilitiesNo: entity.meterAddr, //设施编号
            streetLampType: entity.streetLampType, //路灯类型
            address: entity.address, //地址
            jwdInfo: entity.lngLat, //经纬度
            // powerUnit: entity.powerUnit,//权属单位
            deptid: entity.deptid,
            streetLampId: id
          });
          console.log(entity)
        }
      }
    })
  },
  //查询集合获取终端编号
  searchEXlist: function () {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded'
    };
    let params = {
      deptId: wx.getStorageSync('deptId'),
    }
    var encodingStr = app.ecbEncrypto(params);
    wx.request({
      url: app.url + '/web/exceptionReport/select.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          that.setData({
            exlist: rest.result,
            moreChflag: false
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  inputComChange(e) {
    var key = e.target.dataset.key;
    console.log(key)
    var val = e.detail.value;
    var callback = e.target.dataset.callback;
    this.setData({
      [key]: val
    })
    if (callback) {
      this[callback]()
    }

  },
  changePdxWx() {
    let xlDescription = '';
    this.data.pdxWx[this.data.faultDescription].forEach((item, index) => {
      xlDescription += ((index == 0 ? '' : ',') + item.value + item.name)
    });
    this.setData({
      xlDescription
    })
  },
  //为空判断
  getValue: function (e) {
    var that = this;
    var param = e.target.dataset.param;
    var val = e.detail.value;
    if (param == 1) {
      that.setData({
        facilitiesNo: val.trim()
      });
    } else if (param == 2) {
      that.setData({
        streetLampType: val.trim()
      });
    } else if (param == 3) {
      that.setData({
        address: val.trim()
      });
    } else if (param == 4) {
      that.setData({
        jwdInfo: val.trim()
      });
    }
    // else if (param == 5){
    //   that.setData({ powerUnit: val.trim() });
    // } 
    else if (param == 6) {
      that.setData({
        name: val.trim()
      });
    } else if (param == 7) {
      that.setData({
        phone: val.trim()
      });
    } else if (param == 8) {
      that.setData({
        remark: val.trim()
      });
    }
  },
  faultChange(e) {
    const cboxs = e.detail.value;
    var val = cboxs.toString();
    var faultList = this.data.faultList;
    faultList.forEach((item, index) => {
      item.checked = cboxs.indexOf(item.value) > -1
    })
    var faultItems = this.data.faultItems;
    if (faultItems[this.data.faultChangeValue]) {
      faultItems[this.data.faultChangeValue].forEach((item) => {
        item.checked = false
      })
    }
    var xlItems = this.data.measures;
    if (xlItems[this.data.faultDescription]) {
      xlItems[this.data.faultDescription].forEach((item) => {
        item.checked = false
      })
    }
    this.setData({
      faultChangeValue: val,
      faultList,
      faultDescription: '',
      xlDescription: '',
      faultItems,
    });
  },
  checkboxChange: function (e) {
    var cboxs = e.detail.value;
    console.log(cboxs);
    var faultItems = this.data.faultItems;
    var val = cboxs.toString();
    if (typeof cboxs !== 'string') {
      if(cboxs[cboxs.length - 1] === '其它情况') {
        val = '其它情况'
        faultItems[this.data.faultChangeValue].forEach((item, index) => {
          item.checked = item.value == '其它情况'
        })
      } else {
        faultItems[this.data.faultChangeValue].forEach((item, index) => {
          item.checked =  cboxs.indexOf(item.value) > -1 && item.value !== '其它情况'
        })
      }
      
    } else {
      faultItems[this.data.faultChangeValue].forEach((item, index) => {
        item.checked = cboxs.indexOf(item.value) > -1
      })
    }

    this.setData({
      faultDescription: val,
      faultItems,
      xlDescription: '',
    });
    console.log(this.data.faultDescription);
  },
  xlcheckboxChange: function (e) {
    var cboxs = e.detail.value;
    var xlItems = this.data.measures;
    var val = cboxs.toString();
    xlItems[this.data.faultDescription].forEach((item, index) => {
      item.checked = cboxs.indexOf(item.value) > -1
    })
    console.log(val)
    this.setData({
      xlDescription: val,
      measures: xlItems,
    });
  },
  exsubmit: function (type) {
    var that = this;
    var id = this.data.id;
    const {
      faultDescription,
      faultDescriptionInput
    } = this.data;
    const result = faultDescription == '其它情况' ? faultDescriptionInput : faultDescription
    var params = {
      reportId: id,
      userName: wx.getStorageSync('userName'),
      nickname: wx.getStorageSync('nickname'),
      remark: this.data.remark,
      userId: wx.getStorageSync('userId'),
      result,
      fault: this.data.xlDescription,
      imgDealUrl: this.data.imgUrl.toString(),
      type: 1,
    };
    if (!params.result) {
      wx.showToast({
        title: '请选择维修结果',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    console.log(params)
    wx.request({
      url: url + '/web/exceptionReport/wxdelById.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          wx.navigateBack({
            delta: 2
          })

        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },
  clickFun: function (e) {
    var id = e.currentTarget.dataset.id;
    var ob = e.currentTarget.dataset.ob;
    this.setData({
      radioVal: id,
      exobj: ob
    });
  },
  sureButton: function () {
    var that = this;
    that.setData({
      moreChflag: true,
      facilitiesNo: that.data.exobj.meterAddr,
      address: that.data.exobj.address,
      jwdInfo: that.data.exobj.lngLat,
      deptid: that.data.exobj.deptid,
      streetLampType: that.data.exobj.streetLampType, //路灯类型
      // powerUnit: that.data.exobj.powerUnit,//权属单位
      streetLampId: that.data.exobj.id
    });
  },
  hideMoreCh: function () {
    this.setData({
      moreChflag: true
    })
  },
  mapshow: function () {
    this.setData({
      mapshow: !this.data.mapshow
    })
  },
  openMap: function (event) {
    var that = this
    if (this.data.jwdInfo != "") {
      that.setData({
        longitude: parseFloat(this.data.jwdInfo.split(',')[0]),
        latitude: parseFloat(this.data.jwdInfo.split(',')[1])
      })

      wx.navigateTo({
        url: '../control/query?latitude=' + that.data.latitude + '&longitude=' + that.data.longitude,
      })
    }
  },
  chooseImage(e) {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Accept-Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-CN,zh; q=0.8',
      'Accept': '*/*',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Length': '64',
      'Pragma': 'no-cache',
    };
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;

        tempFilePaths.forEach((item, index) => {
          if (index < 5) {
            wx.uploadFile({
              url: app.url + '/api/account/wxupload.htm',

              filePath: item,
              name: 'file',
              formData: {
                'user': 'test'
              },
              success(res) {
                console.log(res.data)
                var imgUrlList = that.data.imgUrl
                imgUrlList = imgUrlList.concat([res.data])

                var imgshowList = that.data.imgshow;
                imgshowList = imgshowList.concat([item])

                that.setData({
                  imgUrl: imgUrlList,
                  imgshow: imgshowList,
                })
              }
            })
          }

        })

        console.log(tempFilePaths);



      }
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: '86881114',
    })
  },
  deleteImg(e) {
    var index = e.currentTarget.dataset.index;
    var imgUrlList = this.data.imgUrl
    var imgshowList = this.data.imgshow;
    imgUrlList.splice(index, 1)
    imgshowList.splice(index, 1)
    this.setData({
      imgUrl: imgUrlList,
      imgshow: imgshowList,
    })
  }
})